<template>
  <div class="dish-container">
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="form-inline">
        <el-form-item label="菜品名称">
          <el-input v-model="filterForm.name" placeholder="请输入菜品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="菜品分类">
          <el-select v-model="filterForm.categoryId" placeholder="请选择" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd">新增菜品</el-button>
      <el-button type="danger" :disabled="!multipleSelection.length" @click="handleBatchDelete">批量删除</el-button>
    </div>
    
    <el-table
      :data="dishList"
      border
      style="width: 100%"
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="name"
        label="菜品名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="image"
        label="图片"
        width="120">
        <template slot-scope="scope">
          <el-image 
            style="width: 60px; height: 60px"
            :src="scope.row.image" 
            fit="cover"
            :preview-src-list="[scope.row.image]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="categoryName"
        label="分类"
        width="120">
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        width="120">
        <template slot-scope="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="180">
      </el-table-column>
      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getDishPage,
  // addDish, // 在列表页面不需要使用，仅在新增页面使用
  // updateDish, // 在列表页面不需要使用，仅在编辑页面使用
  deleteDish,
  // getDishById, // 在列表页面不需要使用，仅在编辑页面使用
  // getDishList, // 在列表页面不需要使用
  updateDishStatus
} from '@/api/dish'
import { getCategoryList } from '@/api/category'

export default {
  name: 'DishManagement',
  data() {
    return {
      // 筛选表单
      filterForm: {
        name: '',
        categoryId: '',
        status: ''
      },
      // 分类选项
      categoryOptions: [],
      // 菜品列表
      dishList: [],
      // 多选
      multipleSelection: [],
      // 加载状态
      loading: false,
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    // 获取分类列表
    this.fetchCategoryOptions()
    // 获取菜品列表
    this.fetchDishList()
  },
  methods: {
    // 获取分类选项
    fetchCategoryOptions() {
      // 获取菜品分类（type=1）
      getCategoryList(1)
        .then(res => {
          if (res.code === 1) {
            this.categoryOptions = res.data || []
          } else {
            this.$message.error(res.msg || '获取分类列表失败')
          }
        })
        .catch(err => {
          console.error('获取分类列表失败', err)
          this.$message.error('获取分类列表失败')
        })
    },
    
    // 获取菜品列表
    fetchDishList() {
      this.loading = true
      const params = {
        page: this.currentPage,
        pageSize: this.pageSize,
        name: this.filterForm.name,
        categoryId: this.filterForm.categoryId,
        status: this.filterForm.status
      }

      // 处理筛选参数
      if (params.name === '') delete params.name
      if (params.categoryId === '') delete params.categoryId
      if (params.status === '') delete params.status
      
      getDishPage(params)
        .then(res => {
          if (res.code === 1) {
            this.dishList = res.data.records || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.msg || '获取菜品列表失败')
          }
        })
        .catch(err => {
          console.error('获取菜品列表失败', err)
          this.$message.error('获取菜品列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 查询
    handleSearch() {
      this.currentPage = 1
      this.fetchDishList()
    },
    
    // 重置表单
    resetForm() {
      this.filterForm = {
        name: '',
        categoryId: '',
        status: ''
      }
      this.handleSearch()
    },
    
    // 新增菜品
    handleAdd() {
      this.$router.push('/dish/add')
    },
    
    // 编辑菜品
    handleEdit(row) {
      this.$router.push(`/dish/edit/${row.id}`)
    },
    
    // 删除菜品
    handleDelete(row) {
      this.$confirm('确认删除该菜品?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteDish(row.id)
          .then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.fetchDishList()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          })
          .catch(err => {
            console.error('删除菜品失败', err)
            this.$message.error('删除菜品失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 批量删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请至少选择一项')
        return
      }
      
      this.$confirm(`确认删除选中的${this.multipleSelection.length}个菜品?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const ids = this.multipleSelection.map(item => item.id).join(',')
        
        deleteDish(ids)
          .then(res => {
            if (res.code === 1) {
              this.$message.success('批量删除成功')
              this.fetchDishList()
            } else {
              this.$message.error(res.msg || '批量删除失败')
            }
          })
          .catch(err => {
            console.error('批量删除菜品失败', err)
            this.$message.error('批量删除菜品失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    
    // 状态变更
    handleStatusChange(row) {
      const status = row.status
      const statusText = status === 1 ? '起售' : '停售'
      
      this.loading = true
      updateDishStatus(row.id, status)
        .then(res => {
          if (res.code === 1) {
            this.$message.success(`菜品「${row.name}」已${statusText}`)
          } else {
            // 恢复原状态
            row.status = status === 1 ? 0 : 1
            this.$message.error(res.msg || `${statusText}失败`)
          }
        })
        .catch(err => {
          // 恢复原状态
          row.status = status === 1 ? 0 : 1
          console.error(`${statusText}菜品失败`, err)
          this.$message.error(`${statusText}菜品失败`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 多选变更
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    
    // 页码改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchDishList()
    },
    
    // 每页条数改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1 // 切换每页条数时重置为第一页
      this.fetchDishList()
    }
  }
}
</script>

<style scoped>
.dish-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>